package com.zz.check;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;

import org.objectweb.asm.ClassReader;

import com.zz.check.meta.ClassInfo;
import com.zz.check.meta.JarInfo;
import com.zz.check.util.JarCompileCheckUtil;

public class AnalyzeOneJar implements Runnable {
	
	private File file;
	private JarInfo jarInfo;
	public AnalyzeOneJar(File file,JarInfo jarInfo){
		this.file = file;
		this.jarInfo = jarInfo;
	}
	public void run() {
		analyzeOneJar();
	}
	/**
	 * 分析一个jar并为其设置相关信息
	 * @param filePath
	 * @return
	 */
	private void analyzeOneJar(){
			long start = System.currentTimeMillis();
		    DependencyVisitor v = null;
	        ZipFile zipeFile;
	        int clasCnt=0;
			try {
				ClassInfo classInfo = null;
				jarInfo.setBuildVersion(JarCompileCheckUtil.getBuildVersion(file));
				
				zipeFile = new ZipFile(file);
				Enumeration<? extends ZipEntry> en = zipeFile.entries();
				InputStream in = null;
				while (en.hasMoreElements()) {
					ZipEntry entry = en.nextElement();
					String entryName = entry.getName();
					if (entryName.endsWith(".class")) {
						clasCnt++;
						classInfo = new ClassInfo(entryName,zipeFile.getName());
						 v = new DependencyVisitor(classInfo);
						 in = zipeFile.getInputStream(entry);
						 new ClassReader(in).accept(v, 0);
						 
						 //设置jarinfo
						 jarInfo.setName(zipeFile.getName());
						 jarInfo.addOwnedClasses(classInfo.getName());
						 jarInfo.addOwnedPackages(classInfo.getPackageName());
						 jarInfo.addDependentClasses(classInfo.getDependentClasses());
						 in.close();
					}
				}
				zipeFile.close();
				
			} catch (IOException e) {
				e.printStackTrace();
			}
			System.out.println(file.getName()+"解析结束，共"+clasCnt+" 个类文件,耗时： "+(System.currentTimeMillis()-start)+"毫秒");
	}
}
